package ui;

import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.SpringLayout;

import nl.hanze.gameserver.app.Application;
import Client.Command;
import Games.Othello;
import Games.TicTacToe;
import Games.ComputerPlayer;
import Games.TicTacToeComputer;

public class Main extends JPanel implements ActionListener {

    private static JPanel rightJPanel, gamesPanel, rightServerJPanel;
    private static JButton startBtn, loginBtn, startServerGameBtn;
    private JRadioButton playerVsPlayer, playerVsComputer, computerVsComputer, serverPlayer, serverComputerPlayer;
    private JLabel labelPlayer1, labelPlayer2, labelServerIp, labelServerPort, labelserverPlayer;
    private JTextField txtFieldPlayer1, txtFieldPlayer2, txtFieldServerIp, txtFieldServerPort, txtFieldServerPlayer;

    private static ButtonGroup groupServerGamesJRadioBtn = new ButtonGroup();
    private static ButtonGroup groupSinglePlayerGamesJRadioBtn = new ButtonGroup();
    private static ButtonGroup groupSinglePlayerMode = new ButtonGroup();
    
    public final static String TTT = "TicTacToe";
    public final static String OTH = "Othello";
    private final static String PLAYER_VS_PLAYER = "Player vs Player";
    private final static String PLAYER_VS_COMPUTER = "Player vs Computer";
    private final static String COMPUTER_VS_COMPUTER = "Computer vs Computer";
    
    public static boolean ai = false;
    public static boolean mouseInput = true;
    private static Main main;
        
    private static int wins = 0;
    private static int draws = 0;
    private static int losses = 0;
    
    public static boolean multiplayer = false;
    public static boolean received = false;
    
	public Main() {
            main = this;
            init();
	}
        
        public static void startServer(String[] args) {
            Application.main(args);
        }
	
	public void init() {
            setLayout(null);
            groupServerGamesJRadioBtn = new ButtonGroup();
            add(getLeftPanel());
            add(getRightPanel());
	}
	
	public JPanel getLeftPanel() {
            JPanel lp = new JPanel(null);
            lp.setBorder(BorderFactory.createTitledBorder("Computer"));
            lp.setBounds(10, 5, 300, 400);

            //Games panel
            JPanel games = new JPanel(new GridLayout(3,1));
            games.setBorder(BorderFactory.createTitledBorder("Games:"));
            games.setBounds(20, 25, 260, 100);
            
            JRadioButton othello = new JRadioButton("Othello");
            othello.setActionCommand("Othello");
            othello.setSelected(true);
            
            JRadioButton ttt = new JRadioButton("TicTacToe");
            ttt.setActionCommand("TicTacToe");
            
            groupSinglePlayerGamesJRadioBtn.add(othello);
            groupSinglePlayerGamesJRadioBtn.add(ttt);
            
            games.add(othello);
            games.add(ttt);
           
            //Modes panel
            JPanel modes = new JPanel(new GridLayout(3,1));
            modes.setBorder(BorderFactory.createTitledBorder("Mode:"));
            modes.setBounds(20, 135, 260, 105);

            playerVsPlayer = new JRadioButton("Player vs Player");
            playerVsComputer = new JRadioButton("Player vs Computer");
            computerVsComputer = new JRadioButton("Computer vs Computer");

            playerVsPlayer.addActionListener(this);
            playerVsPlayer.setActionCommand(PLAYER_VS_PLAYER);
            
            playerVsComputer.addActionListener(this);
            playerVsComputer.setActionCommand(PLAYER_VS_COMPUTER);
            
            computerVsComputer.addActionListener(this);
            computerVsComputer.setActionCommand(COMPUTER_VS_COMPUTER);
            
            groupSinglePlayerMode.add(playerVsPlayer);
            groupSinglePlayerMode.add(playerVsComputer);
            groupSinglePlayerMode.add(computerVsComputer);

            modes.add(playerVsPlayer);
            modes.add(playerVsComputer);
            modes.add(computerVsComputer);

            //defualt setting to start
            playerVsPlayer.setSelected(true);

            //Players panel
            JPanel players = new JPanel();
            SpringLayout layout = new SpringLayout();
            players.setLayout(layout);
            players.setBorder(BorderFactory.createTitledBorder("Players:"));
            players.setBounds(20, 250, 260, 100);

            labelPlayer1 = new JLabel("Player1: ");
            txtFieldPlayer1 = new JTextField();
            txtFieldPlayer1.setPreferredSize(new Dimension(130, 20));
            labelPlayer2 = new JLabel("Player2: ");
            txtFieldPlayer2 = new JTextField();
            txtFieldPlayer2.setPreferredSize(new Dimension(130, 20));

            players.add(labelPlayer1);
            players.add(txtFieldPlayer1);
            players.add(labelPlayer2);
            players.add(txtFieldPlayer2);

            SpringUtilities.makeCompactGrid(players,
            2, 2, //rows, cols
            4, 4,        //initX, initY
            4, 4);       //xPad, yPad

            //Start Btn
            startBtn = new JButton("start");
            startBtn.setBounds(182, 357, 100, 30);
            startBtn.addActionListener(this);

            lp.add(games);
            lp.add(modes);
            lp.add(players);
            lp.add(startBtn);

            return lp; 
	}
	
	public JPanel getRightPanel()
	{
		rightJPanel = new JPanel(null);
		rightJPanel.setBorder(BorderFactory.createTitledBorder("Network"));
		rightJPanel.setBounds(320, 5, 300, 400);
		
		//Server Panel
		JPanel serverInfoPanel = new JPanel();
		SpringLayout layout = new SpringLayout();
		serverInfoPanel.setLayout(layout);
		serverInfoPanel.setBorder(BorderFactory.createTitledBorder("Server:"));
		serverInfoPanel.setBounds(20, 25, 260, 100);
		
		labelServerIp = new JLabel("Server IP: ");
		txtFieldServerIp = new JTextField("localhost");
		txtFieldServerIp.setPreferredSize(new Dimension(130, 20));
		labelServerPort = new JLabel("Port: ", JLabel.RIGHT);
		txtFieldServerPort = new JTextField("7789");
		txtFieldServerPort.setPreferredSize(new Dimension(130, 20));
		
		serverInfoPanel.add(labelServerIp);
		serverInfoPanel.add(txtFieldServerIp);
		serverInfoPanel.add(labelServerPort);
		serverInfoPanel.add(txtFieldServerPort);
		
		SpringUtilities.makeCompactGrid(serverInfoPanel,
                2, 2, //rows, cols
                4, 4,        //initX, initY
                4, 4);       //xPad, yPad
		
		//Server mode
		JPanel playerMode = new JPanel(new GridLayout(3,1));
		playerMode.setBorder(BorderFactory.createTitledBorder("Mode:"));
		playerMode.setBounds(20, 135, 260, 105);
		
		
		serverPlayer = new JRadioButton("Player");
		serverComputerPlayer = new JRadioButton("Computer");
		playerMode.add(serverPlayer);
		playerMode.add(serverComputerPlayer);
		
		serverPlayer.addActionListener(this);
		serverComputerPlayer.addActionListener(this);
		
		//defualt setting to start
		serverPlayer.setSelected(true);
		
		//Server Panel Mode
		//Players panel
		JPanel serverModePanel = new JPanel();
		SpringLayout layout2 = new SpringLayout();
		serverModePanel.setLayout(layout2);
		serverModePanel.setBorder(BorderFactory.createTitledBorder("Player:"));
		serverModePanel.setBounds(20, 250, 260, 68);
		
		labelserverPlayer = new JLabel("Player: ");
		txtFieldServerPlayer = new JTextField();
		txtFieldServerPlayer.setPreferredSize(new Dimension(130, 20));
		
		serverModePanel.add(labelserverPlayer);
		serverModePanel.add(txtFieldServerPlayer);
		
		SpringUtilities.makeCompactGrid(serverModePanel,
                1, 2, //rows, cols
                4, 4,        //initX, initY
                4, 4);       //xPad, yPad
	
		//Login Btn
		loginBtn = new JButton("Login");
		loginBtn.setBounds(182, 357, 100, 30);
		loginBtn.addActionListener(this);
		
		rightJPanel.add(serverInfoPanel);
		rightJPanel.add(playerMode);
		rightJPanel.add(serverModePanel);
		rightJPanel.add(loginBtn);
		
		return rightJPanel;
	}
	
	public static JPanel getServerSpellen()
	{
		rightServerJPanel = new JPanel(null);
		rightServerJPanel.setBorder(BorderFactory.createTitledBorder("Network"));
		rightServerJPanel.setBounds(320, 5, 300, 400);
		
		//Games panel
		gamesPanel = new JPanel(new GridLayout(8, 1));
		gamesPanel.setBorder(BorderFactory.createTitledBorder("Games:"));
		gamesPanel.setBounds(20, 25, 260, 300);
		
		//Login Btn
		startServerGameBtn = new JButton("Start");
		startServerGameBtn.setBounds(182, 357, 100, 30);
		startServerGameBtn.addActionListener(main);
		
		rightServerJPanel.add(gamesPanel);
		rightServerJPanel.add(startServerGameBtn);
		
		return rightServerJPanel;
	}
	
	
	@Override
	public void actionPerformed(ActionEvent e) {		
		//Computer Modes Action....
		if(playerVsPlayer == e.getSource())
		{
			txtFieldPlayer1.setEditable(true);
			txtFieldPlayer2.setEditable(true);
			playerVsPlayer.setSelected(true);
			playerVsComputer.setSelected(false);
			computerVsComputer.setSelected(false);
			
			txtFieldPlayer1.setText("");
			txtFieldPlayer2.setText("");
		}
		
		if(playerVsComputer == e.getSource())
		{
			txtFieldPlayer1.setEditable(true);
			txtFieldPlayer2.setEditable(true);
			playerVsComputer.setSelected(true);
			playerVsPlayer.setSelected(false);
			computerVsComputer.setSelected(false);
			
			txtFieldPlayer1.setText("GroepB");
			txtFieldPlayer2.setText("Computer");
		}
		
		if(computerVsComputer == e.getSource())
		{
			computerVsComputer.setSelected(true);
			playerVsPlayer.setSelected(false);
			playerVsComputer.setSelected(false);
			
			txtFieldPlayer1.setText("Computer1");
			txtFieldPlayer2.setText("Computer2");
			txtFieldPlayer1.setEditable(false);
			txtFieldPlayer2.setEditable(false);
		}
		//Network Modes
		if(serverPlayer == e.getSource()) {
                serverPlayer.setSelected(true);
                serverComputerPlayer.setSelected(false);
                txtFieldServerPlayer.setText("");
                ai = false;
                    mouseInput = true;
		}
		if(serverComputerPlayer == e.getSource()) {
                    serverComputerPlayer.setSelected(true);
                    serverPlayer.setSelected(false);
                    txtFieldServerPlayer.setText("Computer");
                    ai = true;
                    mouseInput = false;
		}
		if(loginBtn == e.getSource())
		{   
            //check if all fields is filled... 
            if(txtFieldServerIp.getText().isEmpty() || txtFieldServerPort.getText().isEmpty() || txtFieldServerPlayer.getText().isEmpty()) {
                    
            String message = "Please fill in all required fields:"
            + "\n- Server IP"
            + "\n- Port"
            + "\n- Player";
            showMessageDialog(this,message);
            } else {
                //check if it's possible to connect...
                if(Command.connect(txtFieldServerIp.getText(), Integer.parseInt(txtFieldServerPort.getText()))) {
                    //Login server...
                    Command.login(txtFieldServerPlayer.getText());
                    	
                } else {
                    String message = "Could not connect to the server!"
                                        + "\nPossible cause:"
                                        + "\n-Check if the IP of the Server is correct."
                                        + "\n-Check if the Server is Started.";
                    showMessageDialog(this,message);
                }
            }
		}
		//Start local game
		if(startBtn == e.getSource()) {
            
			if(getSelectedSinglePlayerGame() != null){
			
				//Selected game: TicTacToe...
				if(getSelectedSinglePlayerGame().equals(TTT))
                {
					//Slected player mode: Player vs Player
					if(getSelectedSinglePlayerMode().equals(PLAYER_VS_PLAYER)){
						
						String message = PLAYER_VS_PLAYER + " is NOT implemented !"
			                + "\nPlease select another Player Mode";
						showMessageDialog(this, message);
					
				    //Slected player mode: Player vs Computer
					}else if(getSelectedSinglePlayerMode().equals(PLAYER_VS_COMPUTER)){
						
						if(!txtFieldPlayer1.getText().isEmpty() && !txtFieldPlayer2.getText().isEmpty()){
							
							Command.connect("localhost", 7789);
							Command.login(txtFieldPlayer1.getText());
							TicTacToe ttt = new TicTacToe(txtFieldPlayer1.getText(), getSelectedSinglePlayerGame());
							new ComputerPlayer(txtFieldPlayer2.getText(), ttt.getGamesModel());
							
						}else{
							String message = "Could not start a game!"
			                + "\nPossible cause:"
			                + "\n-Fill all required fields: Player1 and Player2";
							showMessageDialog(this,message);
						}
				    
				    //Slected player mode: Compuetr vs Computer	
					}else if(getSelectedSinglePlayerMode().equals(COMPUTER_VS_COMPUTER)){
						//TODO: COMPUTER_VS_COMPUTER for TicTactToe	
						Command.connect("localhost", 7789);
						Command.login(txtFieldPlayer1.getText());
						
						ai = true;
						TicTacToeComputer tttComputer = new TicTacToeComputer(txtFieldPlayer1.getText(), getSelectedSinglePlayerGame());
						new ComputerPlayer(txtFieldPlayer2.getText(), tttComputer.getGamesModel());
					}
						
			    //Selected game: Othello...
                }else if(getSelectedSinglePlayerGame().equals(OTH)) {
                	
                	//Slected player mode: Player vs Player
					if(getSelectedSinglePlayerMode().equals(PLAYER_VS_PLAYER)){
						String message = PLAYER_VS_PLAYER + " is NOT implemented !"
		                + "\nPlease select another Player Mode";
						showMessageDialog(this, message);
					
				    //Slected player mode: Player vs Computer
					}else if(getSelectedSinglePlayerMode().equals(PLAYER_VS_COMPUTER)){
				    
						if(!txtFieldPlayer1.getText().isEmpty() && !txtFieldPlayer2.getText().isEmpty()){
							
							Command.connect("localhost", 7789);
							Command.login(txtFieldPlayer1.getText());
							Othello oth = new Othello(txtFieldPlayer1.getText(), getSelectedSinglePlayerGame());
							new ComputerPlayer(txtFieldPlayer2.getText(), oth.getGamesModel());
							
						}else{
							String message = "Could not start a game!"
			                + "\nPossible cause:"
			                + "\n-Fill all required fields: Player1 and Player2";
							showMessageDialog(this,message);
						}
				    //Slected player mode: Compuetr vs Computer	
					}else if(getSelectedSinglePlayerMode().equals(COMPUTER_VS_COMPUTER)){
						//TODO: COMPUTER_VS_COMPUTER for Othello	
						Command.connect("localhost", 7789);
						Command.login(txtFieldPlayer1.getText());
						
						ai = true;
						Othello oth = new Othello(txtFieldPlayer1.getText(), getSelectedSinglePlayerGame());
						new ComputerPlayer(txtFieldPlayer2.getText(), oth.getGamesModel());
					}
                }
            	
			}else{
				String message = "Could not start a game!"
                + "\nPossible cause:"
                + "\n-Check if you've selected a game.";
				showMessageDialog(this,message);
			}
		}
		//Start server Game
		if(startServerGameBtn == e.getSource()) {
			        
            if (groupServerGamesJRadioBtn.getSelection() != null) {
            	
                if(getSelectedServerGame().equals(TTT))
                {
                    new TicTacToe(txtFieldServerPlayer.getText(), getSelectedServerGame());
                }
                if(getSelectedServerGame().equals(OTH))
                {
                	new Othello(txtFieldServerPlayer.getText(), getSelectedServerGame());
                }
            } else {
                String message = "Could not start a game!"
                                        + "\nPossible cause:"
                                        + "\n-Check if you've selected a game.";
                showMessageDialog(this,message);
            }
		}
	}
        
    public void hideRightJPanel(){
        remove(rightServerJPanel);
        add(rightJPanel);
        repaint();
    }
    
    public void showMessageDialog(Main main,String message) {
        JOptionPane.showMessageDialog(this,message,"Warning:",
        JOptionPane.INFORMATION_MESSAGE);
    }
    
    public static void actionAfterLogin(boolean loginOk, String errMsg){
    	if(loginOk){
    		//Show panels with Game List...
    		main.remove(rightJPanel);
    		main.add(getServerSpellen());
    		main.repaint();   	
    		//get Game list from server..
    		Command.getGameList();
    	}else{
    		String message = "Could not start a game!"
                + "\n" + errMsg;
    		JOptionPane.showMessageDialog(main,message,"Warning:",
    		JOptionPane.INFORMATION_MESSAGE);
    	}
    }
    
	public static void addServerGames(String game, int firstGame){	
		JRadioButton serverGame = new JRadioButton();
	    serverGame.setText(game);
	    serverGame.setActionCommand(game);   
		
	    if(firstGame == 0)
	    	serverGame.setSelected(true);
	    
		gamesPanel.add(serverGame);
	    groupServerGamesJRadioBtn.add(serverGame);
	    gamesPanel.revalidate();
	}
	
	public static void addLocalGames(String game, int firstGame)
	{
		JRadioButton serverGame = new JRadioButton();
	    serverGame.setText(game);
	    serverGame.setActionCommand(game);   
		
	    if(firstGame == 0)
	    	serverGame.setSelected(true);
	    
		gamesPanel.add(serverGame);
	    groupServerGamesJRadioBtn.add(serverGame);
	    gamesPanel.revalidate();
	}
	
	private String getSelectedServerGame(){
		return groupServerGamesJRadioBtn.getSelection().getActionCommand();
	}
	
	private String getSelectedSinglePlayerMode(){
		return groupSinglePlayerMode.getSelection().getActionCommand();
	}
	
	private String getSelectedSinglePlayerGame(){
		return groupSinglePlayerGamesJRadioBtn.getSelection().getActionCommand();
	}
  
	public static void main(String[] args) {
            startServer(args);
	    JFrame frame = new JFrame();
	    frame.getContentPane().add(new Main());
	    
	    Toolkit toolkit = frame.getToolkit();
            Dimension screensize = toolkit.getScreenSize();
  
            frame.setLocation((screensize.width/2) - (800/2), (screensize.height/2) - (400/2) - 160);        
	    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	    frame.setPreferredSize(new Dimension(630,435));
	    frame.setSize(630,435);
	    frame.setResizable(false);
	    frame.setVisible(true);
	}
        
    public static void addWin() {
        wins += 1;
    }
    
    public static void addDraw() {
        draws += 1;
    }
    
    public static void addLoss() {
        losses += 1;
    }
    
    public static int getWins(){
        return wins;
    }
    
    public static int getDraws(){
        return draws;
    }
    
    public static int getLosses() {
        return losses;
    }
}